package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.model.mongo.UserLocation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 搜附近服务接口实现类
 */
@DubboService
@Slf4j
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 上报地理位置
     *
     * @param latitude  纬度  y   22.581672 (纬度范围是0-90°)
     * @param longitude 经度  x  113.870096 (经度范围是0-180)
     * @param addrStr   位置描述
     * @param userId    当前登录用户id
     */
    @Override
    public void addLocation(Double latitude, Double longitude, String addrStr, Long userId) {

        //1.根据当前登录用户id查询userLocation表记录是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        if (mongoTemplate.exists(query, UserLocation.class)) {
            //2.如果存在，则更新数据
            Update update = new Update();
            //double x, double y  y表示当地的纬度，x表示当地的经度
            update.set("location", new GeoJsonPoint(longitude, latitude));//经纬度
            update.set("address", addrStr);//中文地址位置名称
            update.set("updated", System.currentTimeMillis());
            mongoTemplate.updateFirst(query, update, UserLocation.class);
        } else {
            //3.如果不存在，则保存数据
            long nowTime = System.currentTimeMillis();
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);//登录用户id
            //GeoJsonPoint（x大值,y小值）
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(nowTime);
            userLocation.setUpdated(nowTime);
            mongoTemplate.insert(userLocation);
        }
    }

    /*
     *搜附近
     * distance：单位米
     */
    @Override
    public List<Long> searchNearUser(Long loginUserId, Long distance) {
        log.debug("**************loginUserId****{}*******distance***{}********",loginUserId,distance);
        //1.获取当前登录用户位置（圆心点）
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(loginUserId));
        UserLocation myUserLocation = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint loginUserLocation = myUserLocation.getLocation(); //当前用户位置经纬度
        //2.根据圆心点 和 搜索距离 构建条件
        Query nearQuery = new Query();
        //Point:圆心点 Distance:搜索距离
        //double value, Metric metric
        Circle circle = new Circle(loginUserLocation,new Distance(distance/1000, Metrics.KILOMETERS));//圆对象
        //搜索距离条件  +  排除自己这条数据
        nearQuery.addCriteria(Criteria.where("location").withinSphere(circle).and("userId").ne(loginUserId));
        //3.调用mongdb方法查询附近用户数据list<UserLocation>集合
        List<UserLocation> userLocationList = mongoTemplate.find(nearQuery, UserLocation.class);
        log.debug("**************userLocationList****{}*******",userLocationList);
        if(CollectionUtils.isEmpty(userLocationList)){
            return null;
        }
        //4.根据list集合数据获取list<Long>
        return userLocationList.stream().map(UserLocation::getUserId).collect(Collectors.toList());
    }
}
